package com.logreview.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class DES {

	/**
	 * 加密
	 * 
	 * @param src
	 *            byte[]
	 * @param key
	 *            byte[]
	 * @return byte[]
	 */
	public static byte[] encrypt(byte[] src, byte[] key) {
		try {
			DESKeySpec desKey = new DESKeySpec(key);
			// 创建一个密匙工厂，然后用它把DESKeySpec转换成
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// 将DESKeySpec对象转换成SecretKey对象
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成加密操作
			Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, securekey, new IvParameterSpec(desKey.getKey()));
			// 现在，获取数据并加密
			// 正式执行加密操作
			return cipher.doFinal(src);
		} catch (Throwable e) {
			e.printStackTrace();
			return null;
		}
		
	}

	/**
	 * 解密
	 * 
	 * @param src
	 *            byte[]
	 * @param key
	 *            byte[]
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] src, byte[] key) {
		try {
			// 创建一个DESKeySpec对象
			DESKeySpec desKey = new DESKeySpec(key);
			// 创建一个密匙工厂
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// 将DESKeySpec对象转换成SecretKey对象
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, new IvParameterSpec(desKey.getKey()));
			// 真正开始解密操作
			return cipher.doFinal(src);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}

	// 测试
	public static void main(String args[]) {
		// 待加密内容
		String str = "abcdefgh";
		// 密码，长度要是8的倍数
		String password = "12345678";

		byte[] src = str.getBytes();
		
		byte[] result = DES.encrypt(src, password.getBytes());
		System.out.println("加密后：" + new String(result));
		// 直接将如上内容解密
		try {
			byte[] decryResult = DES.decrypt(result, password.getBytes());
			System.out.println("解密后：" + new String(decryResult));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
}
